/** https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
 * Tip: Optimizing Performance by Skipping Effects*/
import React, {useEffect, useState} from 'react';

/* 类里我们这样优化副作用
componentDidUpdate(prevProps, prevState) {
  if (prevState.count !== this.state.count) {
    document.title = `You clicked ${this.state.count} times`;
  }
}
*/

/* hooks这样优化↓
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
*/

export default function Counter(){
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);

  /* useEffect里的函数会在组件挂载完成后,或则组件更新完成后进行调用
    如果没有给第二个参数 ↑函数会在每次执行渲染后调用
    而如果是空数组 则只会在组件挂载完成执行一次后就不再执行了
    而如果指定了某些个state, 则只有这些个state改变时, 才会触发effect执行(只要数组里依赖的有一个改变就会触发)
  */
  useEffect(() => {
    /** 只有count1改变时才会执行*/
    console.log('trigger effect body,count1 has changed');
    return () => console.log('trigger effect cleanup');
  },[count1]);

  return (
    <div>
      <p>count1:{count1}</p>
      <button onClick={() =>
        setCount1(x=>x+1)
      }>count1+</button>

      <p>count2:{count2}</p>
      {/*↓ 点击下面的button并不会触发effect*/}
      <button onClick={() =>
        setCount2(x=>x+1)
      }>count2+</button>
    </div>
  );
}
